package com.wensi.module_app_manager

import android.os.Handler
import android.os.Message
import android.view.View
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.wensi.adapter.BasePagerAdapter
import com.wensi.helper.ARouterHelper
import com.wensi.helper.AppHelper
import com.wensi.lib_base.BaseActivity
import kotlinx.android.synthetic.main.activity_app_manager.*

@Route(path = ARouterHelper.PATH_APP_MANAGER)
class ManagerActivity : BaseActivity() {
    private val waitApp = 1000
    private val handler:Handler = object: Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == waitApp) {
                waitForInitViewPager()
            }
        }
    }
    override fun getLayoutId(): Int {
        return R.layout.activity_app_manager
    }

    override fun getTitleText(): String {
        return getString(R.string.manager_name)
    }

    override fun isShowBack(): Boolean {
        return true
    }

    override fun initView() {
        llLoading.visibility = View.VISIBLE
        waitForInitViewPager()
    }

    /**
     * 等待应用加载完成并初始化viewpager
     */
    private fun waitForInitViewPager() {
        if (AppHelper.allAppViewList.size > 0) {
            initViewPager()
        } else {
            handler.sendEmptyMessageDelayed(waitApp, 1000)
        }
    }
    private fun initViewPager() {
        viewPager.offscreenPageLimit = AppHelper.getPageSize()
        viewPager.adapter = BasePagerAdapter(AppHelper.allAppViewList)
        llLoading.visibility = View.GONE
        pointLayoutView.setPointSize(AppHelper.getPageSize())
        viewPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                pointLayoutView.setChecked(position)
            }
        })
    }
}
